package com.android.dwt.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.dwt.R;
import com.android.dwt.TaskItem;
import com.android.dwt.data.DBTaskAdapter;
import com.android.dwt.data.GTDApp;
import com.android.dwt.ui.MainAct;
import com.android.dwt.ui.NewTaskAct;
import com.android.dwt.ui.TaskDetailAct;
import com.android.dwt.ui.ViewTaskAct;
import com.android.dwt.util.C;
import com.android.dwt.util.TaskUtil;


public class TodayFrag extends ListFragment {
	
	private static final String TAG = "TodayFrag	";
	
	private boolean mHasTask;
	
	private ArrayList<HashMap<String, Object>> mData = new ArrayList<HashMap<String, Object>>();
	private final String[] mFrom = new String[] { "item_time", "item_title" };
	private final int[] mTo = new int[] { R.id.tv_day_time, R.id.tv_day_task };
	
	private MainAct mMain;
	private MyAdapter mAdapter;
	private String mToday;
	private ListView mList;
	private GTDApp mGa;
	private ImageButton mAddTask;
	private long mRowId;
	
	private View mTask;
	private View mEmpty;
	
	private Resources mRsrc;
	private SimpleDateFormat mSdfDate = new SimpleDateFormat("yyyy-MM-dd");
	
	
	public static TodayFrag newInstance() {
    	
		TodayFrag today = new TodayFrag();

        /*Bundle args = new Bundle();
        args.putBoolean("has_task", hasTask);
        today.setArguments(args);*/
        
        Log.e(TAG, "today id: " + today.getId());

        return today;
    }

		
	@Override
	public void onAttach(Activity activity) {
		
		Log.e(TAG, "onAttach is called! ");
		
		super.onAttach(activity);
		
		mMain = (MainAct) activity;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		Log.e(TAG, "onCreate is called! ");
		
		super.onCreate(savedInstanceState);
		
		mGa = (GTDApp) mMain.getApplication();
		mRsrc = getResources();
		
		mToday = mSdfDate.format(Calendar.getInstance().getTime());
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		Log.e(TAG, "onCreateView is called!");
		
//    		return super.onCreateView(inflater, container, savedInstanceState);
		
		View view = inflater.inflate(R.layout.panel_today, container, false);
		
		return view;
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		
		super.onViewCreated(view, savedInstanceState);
		
		mTask = view.findViewById(R.id.ll_day_list);
		mEmpty = view.findViewById(R.id.ll_day_empty);
		
		getAdapterData();
		if (mData.size() == 0) {
			
			mTask.setVisibility(View.GONE);
			mEmpty.setVisibility(View.VISIBLE);
			
		} else {
			
			mEmpty.setVisibility(View.GONE);
			mTask.setVisibility(View.VISIBLE);
			
			(view.findViewById(R.id.fl_top)).setVisibility(View.GONE);
			
			initView();
		}
		
		mAddTask = (ImageButton) view.findViewById(R.id.btn_today_new);
		mAddTask.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Intent i = new Intent(mMain, NewTaskAct.class);
				
				i.putExtra("list_index", GTDApp.AGENDA);
				i.putExtra("new_task", true);
				
				i.putExtra("selected_date", mToday);
				
				startActivityForResult(i, 0);
			}
		});
		mAddTask.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					
					v.setBackgroundResource(R.drawable.add_btn_pressed);
					
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					
					v.setBackgroundResource(R.drawable.add_task);
				}

				return false;
			}
			
		});
		
		return;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		
		super.onActivityCreated(savedInstanceState);
		
	}
	
	@Override
	public void onDestroyView() {
		
		Log.e(TAG, "onDestroyView is called!");
		
		super.onDestroyView();
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		
		super.onSaveInstanceState(outState);
		
		/*outState.putInt("year", mYear);
		outState.putInt("month", mMonth);
		outState.putInt("day", mDay);*/
		
//		fillData();
	}
	
	@Override
	public void onResume() {

		Log.e(TAG, "onResume is called!");
		
		super.onResume();
		
		updateAdapterView();
	}
	
	@Override
	public void onDestroy() {
		
		Log.e(TAG, "onDestroy is called!");
		
		super.onDestroy();
	}
	
	private void initView() {
		
		mList = getListView();
		
		mAdapter = new MyAdapter(
				mMain,
				mData,
				R.layout.row_agenda,
				mFrom,
				mTo);
		mList.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
		
		registerForContextMenu(mList);
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		
		super.onListItemClick(l, v, position, id);
		
		long rowId = (Long) mData.get(position).get("item_id");
//    		TaskItem task = mGa.getDbta().getTaskItem(rowId);
		
		Intent i = new Intent(mMain, TaskDetailAct.class);
		
		i.putExtra("row_id", rowId);
//    		i.putExtra("list_index", GTDApp.AGENDA);
//    		i.putExtra("task", task);
//    		i.putExtra("selected_date", mToday);
		
		startActivityForResult(i, 0);
	}
	
	public void updateAdapterView() {
		
		refreshAdapterData();
		
//		final FragmentTransaction transaction = mMain.getSupportFragmentManager().beginTransaction();
		
//    		ArrayList<Fragment> al = mMain.getFragments();
//    		al.remove(MainAct.TODAY);
//    		transaction.remove(al.get(MainAct.TODAY));
		
		mMain.updateCounter(mData.size());
		
		if (mData.size() == 0) {
			
			mHasTask = false;
			
			mTask.setVisibility(View.GONE);
			mEmpty.setVisibility(View.VISIBLE);
			
//    			setContentView(R.layout.today_empty);
			
//    			al.add(MainAct.TODAY, TodayAct.newInstance(false));
			
//    			transaction.add(TodayAct.newInstance(false), null);
//			transaction.replace(R.id.fl_container, TodayEmpty.newInstance());
//    			transaction.remove(arg0)
			
//    			mSetLayout = false;
			
		} else {		// there is data
				
			initView();
			
			mHasTask = true;
			
			mEmpty.setVisibility(View.GONE);
			mTask.setVisibility(View.VISIBLE);
			
			(mTask.findViewById(R.id.fl_top)).setVisibility(View.GONE);
				
//    			al.add(MainAct.TODAY, TodayAct.newInstance(true));
			
//    			transaction.add(TodayAct.newInstance(true), null);
//    			transaction.replace(mContainer.getId(), TodayAct.newInstance(true));
			
//			transaction.replace(R.id.fl_container, TodayTask.newInstance());
			
//    			(mMain.findViewById(R.id.fl_top)).setVisibility(View.GONE);
			
//    			initView();
			
//    			mSetLayout = true;
			
    		mAdapter.notifyDataSetChanged();
		}
		
//    		mMain.getViewPager().getAdapter().notifyDataSetChanged();
		
//		transaction.commit();
		
//    		mAdapter.notifyDataSetChanged();
		
//    		Log.e(TAG, "size of fragment: "+al.size());
		
		return;
	}
	
	private void refreshAdapterData() {
		
		getAdapterData();
	}
	
	private void getAdapterData() {
		
		HashMap<String, Object> hm;
		
		mData.clear();
		
		Cursor cursor = mGa.getDbta().getDayTask(mToday);
		
		if (cursor.getCount() > 0) {
			
			cursor.moveToFirst();
			
			do {
				
				hm = new HashMap<String, Object>();
				
				long id = cursor.getLong(DBTaskAdapter.COL_ID);
				String name = cursor.getString(DBTaskAdapter.COL_TASK_NAME);
				int allDay = cursor.getInt(DBTaskAdapter.COL_TASK_STATUS);
				String startTime = cursor.getString(DBTaskAdapter.COL_TASK_ST);
				String endTime = cursor.getString(DBTaskAdapter.COL_TASK_ET);
				String prior = cursor.getString(DBTaskAdapter.COL_TASK_PRIOR);
				
				hm.put("item_id", id);
				
				if (allDay == 1) {		// all day task
					
					hm.put("item_time", "全天");
					
				} else {
					
					String time = startTime.split(" ")[1];
					
					if (endTime.length() > 0) {
						
						hm.put("item_time", time + " ~ " + endTime.split(" ")[1]);
						
					} else {
						
						hm.put("item_time", time);
					}
					
				}
				
				hm.put("item_title", name);
				
				hm.put("item_prior", prior);
				
				mData.add(hm);
				
			} while (cursor.moveToNext());
		}
		
		cursor.close();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		HashMap<String, Object> hm = (HashMap<String, Object>) mList.getItemAtPosition(info.position);
		mRowId = (Long) hm.get("item_id");
		
		menu.setHeaderTitle("编辑任务");
		
		menu.add(0, ViewTaskAct.MOVE_TASK, 0, "移动到");
		menu.add(0, ViewTaskAct.EDIT_TASK, 1, "编辑");
		menu.add(0, ViewTaskAct.REMOVE_TASK, 2, "删除");

	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		
//    		return super.onContextItemSelected(item);
		
		switch (item.getItemId()) {
		
    		case ViewTaskAct.MOVE_TASK:

    			mGa.mRefresh = true;
				TaskUtil.moveTask(mMain, GTDApp.AGENDA, mRowId);
				
				return true;
    			
    		case ViewTaskAct.EDIT_TASK:

    			TaskUtil.editTask(mMain, GTDApp.AGENDA, mRowId);
    			
				return true;
    			
    		case ViewTaskAct.REMOVE_TASK:
    			
    			mGa.mRefresh = true;
				TaskUtil.removeTask(mMain, GTDApp.AGENDA, mRowId);
				
				return true;
    			
    		default:
    			break;
		}
		
		
		
		return false;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		
//    		super.onActivityResult(requestCode, resultCode, intent);
		
		Log.e(TAG, "onActivityResult is called!");
		
//    		refreshAdapterData();
//    		mAdapter.notifyDataSetChanged();
		
		updateAdapterView();
	}
	
	
	/*
	 * Adapter class
	 */
	public class MyAdapter extends SimpleAdapter {
		
		private class ViewHolder {
			
			TextView prior;
			CheckBox cb;
			TextView time;
			TextView title;
			TextView flag;
		}

		
		private LayoutInflater mInflater;
		

		public MyAdapter(Context context, List<? extends Map<String, ?>> data,
				int resource, String[] from, int[] to) {
			
			super(context, data, resource, from, to);
			// TODO Auto-generated constructor stub
			
			mInflater = LayoutInflater.from(context);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
//    			return super.getView(position, convertView, parent);
			
			final ViewHolder holder;
			
			if (convertView == null) {
				
				convertView = mInflater.inflate(R.layout.row_agenda, null);
				
				holder = new ViewHolder();
				
				holder.prior = (TextView) convertView.findViewById(R.id.tv_agenda_prior);
				holder.cb = (CheckBox) convertView.findViewById(R.id.cb_agenda_completed);
				holder.time = (TextView) convertView.findViewById(R.id.tv_agenda_time);
				holder.title = (TextView) convertView.findViewById(R.id.tv_agenda_title);
				holder.flag = (TextView) convertView.findViewById(R.id.tv_agenda_flag);
				
				convertView.setTag(holder);
				
			} else {
				
				holder = (ViewHolder) convertView.getTag();
			}
			
			fillData(holder, position);
			
			return convertView;
		}
		
		private void fillData(final ViewHolder holder, final int position) {
			
			HashMap<String, Object> hm = mData.get(position);
			final long rowId = (Long) hm.get("item_id");
			final TaskItem task = mGa.getDbta().getTaskItem(rowId);
			
			// Priority
			String prior = (String) mData.get(position).get("item_prior");
			if (prior.equals("无")) {
				
				holder.prior.setBackgroundColor(mRsrc.getColor(R.color.none_prior));
				
			} else if (prior.equals("高")) {
				
				holder.prior.setBackgroundColor(mRsrc.getColor(R.color.high_prior));
				
			} else if (prior.equals("中")) {
				
				holder.prior.setBackgroundColor(mRsrc.getColor(R.color.medium_prior));
				
			} else if (prior.equals("低")) {
				
				holder.prior.setBackgroundColor(mRsrc.getColor(R.color.low_prior));
			}

			// CheckBox
			holder.cb.setOnCheckedChangeListener(null);
			holder.cb.setChecked(false);
			
			holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					
					// TODO Auto-generated method stub
					Log.e(TAG, "checkbox " + position + " checked!");
					
					String list = task.getListName();
					int listIndex = TaskUtil.getListIndex(mGa.mList, list);
					
					SharedPreferences prefs = mMain.getSharedPreferences(GTDApp.strList, GTDApp.MODE);
					Editor editor = prefs.edit();

					if (isChecked) {
						
						holder.flag.setVisibility(View.VISIBLE);

						task.setCompletedStatus(C.TASK.COMPLETED);
						mGa.getDbta().updateTask(rowId, task);
						
						if (listIndex != -1) {		// in some list
							
							// update the counter
							int count = (Integer) mGa.lists.get(listIndex).get("item_count");
							mGa.lists.get(listIndex).put("item_count", count-1);
							
							editor.putInt("List_count["+listIndex+"]", count-1);
							
						} else {
							
//    							String list = task.getListName();
							int index = TaskUtil.getListIndex(mGa.mList, list);
							
							int count = (Integer) mGa.lists.get(index).get("item_count");
							mGa.lists.get(index).put("item_count", count-1);
							
							editor.putInt("List_count["+index+"]", count-1);
						}
						
					} else {		// CheckBox is unchecked
						
						holder.flag.setVisibility(View.INVISIBLE);

						task.setCompletedStatus(C.TASK.UNCOMPLETED);
						mGa.getDbta().updateTask(rowId, task);
						
						if (listIndex != -1) {
							
							// update the counter
							int count = (Integer) mGa.lists.get(listIndex).get("item_count");
							mGa.lists.get(listIndex).put("item_count", count+1);
							
							
							editor.putInt("List_count["+listIndex+"]", count+1);
							
						} else {
							
							// get original list index
//    							String list = task.getListName();
							int index = TaskUtil.getListIndex(mGa.mList, list);
							
							Log.e(TAG, "original list and its index are: " + list + " " + index);
							
							int count = (Integer) mGa.lists.get(index).get("item_count");
							mGa.lists.get(index).put("item_count", count+1);
							
							editor.putInt("List_count["+index+"]", count+1);
						}
						
					}
					
					editor.commit();
					
					buttonView.setTag(null);
					
					updateAdapterView();
				}
				
			});		// end $setOnCheckChangeListener
			
			// start and end time
			String time;
			if (task.isAllDay()) {		// all day task
				
				time = "全天";
				
			} else {
				
				String startTime = task.getStartTime();
				String endTime = task.getEndTime();
				time = startTime.split(" ")[1] + " ~ " + endTime.split(" ")[1];
			}
			holder.time.setText(time);
			
			// task title
			holder.title.setText(task.getTaskName());
			
			holder.flag.setVisibility(View.INVISIBLE);
		}		// end $fillData
		
	}		// end class $MyListAdapter
	

}